package com.gitee.dufafei.spark.util

import java.util.Locale

import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, Days, LocalDate}

/**
 * <dependency>
 * <groupId>joda-time</groupId>
 * <artifactId>joda-time</artifactId>
 * <version>2.9.4</version>
 * </dependency>
 */
object TimeUtil {

  val DEFAULT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"
  val DEFAULT_DATE_FORMAT = "yyyy-MM-dd"

  // 获取时间

  def dateTime(time: String, pattern: String = DEFAULT_TIME_FORMAT): DateTime = DateTime.parse(time, DateTimeFormat.forPattern(pattern))

  def dateTime(timestamp: Long): DateTime = new DateTime(timestamp)

  // 获取日期

  def localDate(time: String, pattern: String = DEFAULT_DATE_FORMAT): LocalDate = LocalDate.parse(time, DateTimeFormat.forPattern(pattern))

  def localDate(time: DateTime): LocalDate = time.toLocalDate

  // 转时间戳

  def timestamp(dateTime: DateTime): Long = dateTime.getMillis

  // 转字符串

  def timeString(time: DateTime, pattern: String = DEFAULT_TIME_FORMAT): String = time.toString(pattern, Locale.CHINESE)

  def timeString(timestamp: Long, pattern: String): String = dateTime(timestamp).toString(pattern, Locale.CHINESE)

  def dateString(date: LocalDate, pattern: String = DEFAULT_TIME_FORMAT): String = date.toString(pattern, Locale.CHINESE)

  // 获取两个日期之间的差值

  def getBetweenDays(start: LocalDate, end: LocalDate): Int = Days.daysBetween(start, end).getDays

  def getBetweenDays(start: String, end: String): Int = getBetweenDays(localDate(start), localDate(end))

  // 日期加操作

  def plusDays(date: LocalDate, number: Int): LocalDate = date.plusDays(number)

  def plusDays(date: String, number: Int): LocalDate = plusDays(localDate(date), number)

  // 日期减操作

  def minusDays(date: LocalDate, number: Int): LocalDate = date.minusDays(number)

  def minusDays(date: String, number: Int): LocalDate = minusDays(localDate(date), number)
}
